Telegram Group & Telegram Channel
🖥 Краткое руководство по RegEx в Python

📦 Импорт модуля:

import re

🔍 Основные функции модуля re

re.search(pattern, string) # Находит первое совпадение в любой части строки
re.match(pattern, string) # Проверяет совпадение только в начале строки
re.fullmatch(pattern, string) # Проверяет, соответствует ли вся строка шаблону полностью
re.findall(pattern, string) # Возвращает список всех совпадений
re.finditer(pattern, string) # То же самое, но возвращает итератор с объектами Match
re.sub(pattern, repl, string) # Заменяет найденные по шаблону участки
re.split(pattern, string) # Делит строку по шаблону

# 🧠 Основы синтаксиса шаблонов

| Шаблон | Значение |
|---------|-----------------------------------|
| . | Любой символ, кроме символа новой строки |
| ^ | Начало строки |
| $ | Конец строки |
| * | 0 или более повторений |
| + | 1 или более повторений |
| ? | 0 или 1 повторение |
| {n} | Ровно n повторений |
| {n,} | n или больше повторений |
| {n,m} | От n до m повторений |
| [] | Класс символов |
| [^] | Отрицание класса символов |
| | | Логическое ИЛИ (`a|b`) |
| () | Группа захвата |
| \ | Экранирование специальных символов|

💡 Примеры

re.search(r'\d+', 'ID=12345') # Найдёт '12345' (одна или более цифр)
re.match(r'^\w+$', 'hello_world') # Проверяет, что вся строка состоит из букв, цифр или _
re.findall(r'[A-Z][a-z]+', 'Mr. Smith and Dr. Brown') # ['Smith', 'Brown']
re.sub(r'\s+', '-', 'a b c') # Результат: 'a-b-c'
re.split(r'[;,\s]\s*', 'one, two;three four') # ['one', 'two', 'three', 'four']

🎯 Работа с группами захвата

text = 'Name: John, Age: 30'
match = re.search(r'Name: (\w+), Age: (\d+)', text)
if match:
print(match.group(1)) # John
print(match.group(2)) # 30

Группы можно называть:

pattern = r'(?P<name>\w+): (?P<value>\d+)'
match = re.search(pattern, 'score: 42')
match.group('name') # 'score'
match.group('value') # '42'

🧱 Сложные шаблоны

pattern = r'\b(?:https?://)?(www\.)?\w+\.\w+\b'
text = 'Visit https://example.com or www.test.org'
re.findall(pattern, text) # [['www.'], ['www.']]

⚠️ Полезные рекомендации

• Используйте префикс r'' перед шаблонами, чтобы не нужно было экранировать обратный слэш \
• re.compile(pattern) помогает повысить скорость при многократном использовании шаблона
• Лучше использовать re.search вместо re.match, так как он ищет совпадение в любом месте строки

Быстрая проверка шаблонов

📍 Онлайн-сервисы для тестирования:
- https://regex101.com/
- https://pythex.org/

Если нужна отдельная шпаргалка по re.sub с использованием лямбда-функций, замен и функций внутри, ставь лайк 👍

@Python_Community_ru



tg-me.com/Python_Community_ru/2598
Create:
Last Update:

🖥 Краткое руководство по RegEx в Python

📦 Импорт модуля:

import re

🔍 Основные функции модуля re

re.search(pattern, string) # Находит первое совпадение в любой части строки
re.match(pattern, string) # Проверяет совпадение только в начале строки
re.fullmatch(pattern, string) # Проверяет, соответствует ли вся строка шаблону полностью
re.findall(pattern, string) # Возвращает список всех совпадений
re.finditer(pattern, string) # То же самое, но возвращает итератор с объектами Match
re.sub(pattern, repl, string) # Заменяет найденные по шаблону участки
re.split(pattern, string) # Делит строку по шаблону

# 🧠 Основы синтаксиса шаблонов

| Шаблон | Значение |
|---------|-----------------------------------|
| . | Любой символ, кроме символа новой строки |
| ^ | Начало строки |
| $ | Конец строки |
| * | 0 или более повторений |
| + | 1 или более повторений |
| ? | 0 или 1 повторение |
| {n} | Ровно n повторений |
| {n,} | n или больше повторений |
| {n,m} | От n до m повторений |
| [] | Класс символов |
| [^] | Отрицание класса символов |
| | | Логическое ИЛИ (`a|b`) |
| () | Группа захвата |
| \ | Экранирование специальных символов|

💡 Примеры

re.search(r'\d+', 'ID=12345') # Найдёт '12345' (одна или более цифр)
re.match(r'^\w+$', 'hello_world') # Проверяет, что вся строка состоит из букв, цифр или _
re.findall(r'[A-Z][a-z]+', 'Mr. Smith and Dr. Brown') # ['Smith', 'Brown']
re.sub(r'\s+', '-', 'a b c') # Результат: 'a-b-c'
re.split(r'[;,\s]\s*', 'one, two;three four') # ['one', 'two', 'three', 'four']

🎯 Работа с группами захвата

text = 'Name: John, Age: 30'
match = re.search(r'Name: (\w+), Age: (\d+)', text)
if match:
print(match.group(1)) # John
print(match.group(2)) # 30

Группы можно называть:

pattern = r'(?P<name>\w+): (?P<value>\d+)'
match = re.search(pattern, 'score: 42')
match.group('name') # 'score'
match.group('value') # '42'

🧱 Сложные шаблоны

pattern = r'\b(?:https?://)?(www\.)?\w+\.\w+\b'
text = 'Visit https://example.com or www.test.org'
re.findall(pattern, text) # [['www.'], ['www.']]

⚠️ Полезные рекомендации

• Используйте префикс r'' перед шаблонами, чтобы не нужно было экранировать обратный слэш \
• re.compile(pattern) помогает повысить скорость при многократном использовании шаблона
• Лучше использовать re.search вместо re.match, так как он ищет совпадение в любом месте строки

Быстрая проверка шаблонов

📍 Онлайн-сервисы для тестирования:
- https://regex101.com/
- https://pythex.org/

Если нужна отдельная шпаргалка по re.sub с использованием лямбда-функций, замен и функций внутри, ставь лайк 👍

@Python_Community_ru

BY Python Community




Share with your friend now:
tg-me.com/Python_Community_ru/2598

View MORE
Open in Telegram


Python Community Telegram | DID YOU KNOW?

Date: |

Telegram auto-delete message, expiring invites, and more

elegram is updating its messaging app with options for auto-deleting messages, expiring invite links, and new unlimited groups, the company shared in a blog post. Much like Signal, Telegram received a burst of new users in the confusion over WhatsApp’s privacy policy and now the company is adopting features that were already part of its competitors’ apps, features which offer more security and privacy. Auto-deleting messages were already possible in Telegram’s encrypted Secret Chats, but this new update for iOS and Android adds the option to make messages disappear in any kind of chat. Auto-delete can be enabled inside of chats, and set to delete either 24 hours or seven days after messages are sent. Auto-delete won’t remove every message though; if a message was sent before the feature was turned on, it’ll stick around. Telegram’s competitors have had similar features: WhatsApp introduced a feature in 2020 and Signal has had disappearing messages since at least 2016.

How to Buy Bitcoin?

Most people buy Bitcoin via exchanges, such as Coinbase. Exchanges allow you to buy, sell and hold cryptocurrency, and setting up an account is similar to opening a brokerage account—you’ll need to verify your identity and provide some kind of funding source, such as a bank account or debit card. Major exchanges include Coinbase, Kraken, and Gemini. You can also buy Bitcoin at a broker like Robinhood. Regardless of where you buy your Bitcoin, you’ll need a digital wallet in which to store it. This might be what’s called a hot wallet or a cold wallet. A hot wallet (also called an online wallet) is stored by an exchange or a provider in the cloud. Providers of online wallets include Exodus, Electrum and Mycelium. A cold wallet (or mobile wallet) is an offline device used to store Bitcoin and is not connected to the Internet. Some mobile wallet options include Trezor and Ledger.

Python Community from pl


Telegram Python Community
FROM USA